<template>
  <el-main class="increase-machine-pricing-main">
    <div class="main-container">
      <!-- 查询表单区域 -->
      <el-card class="search-card" shadow="hover">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="配置类型">
            <el-input 
              v-model="searchForm.configurationType" 
              placeholder="请输入配置类型" 
              clearable
              style="width: 220px"
            ></el-input>
          </el-form-item>

          <el-form-item label="项目名称">
            <el-input 
              v-model="searchForm.project" 
              placeholder="请输入项目名称" 
              clearable
              style="width: 220px"
            ></el-input>
          </el-form-item>

          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.activate" 
              placeholder="请选择状态" 
              clearable
              style="width: 120px"
            >
              <el-option label="生效" :value="1"></el-option>
              <el-option label="作废" :value="0"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="配置">
            <el-input 
              v-model="searchForm.configuration" 
              placeholder="请输入配置" 
              clearable
              style="width: 220px"
            ></el-input>
          </el-form-item>

          <el-form-item class="search-buttons">
            <el-button type="primary" @click="fetchData" class="search-btn">
              <i class="el-icon-search"></i>
              查询
            </el-button>
            <el-button @click="resetForm" class="reset-btn">
              <i class="el-icon-refresh"></i>
              重置
            </el-button>
            <el-button type="success" @click="showAddDialog" class="add-btn">
              <i class="el-icon-plus"></i>
              新增
            </el-button>
            <el-button type="success" @click="handleImport" class="import-btn">
              <i class="el-icon-upload2"></i>
              导入
            </el-button>
            <el-button type="info" @click="exportData" class="export-btn">
              <i class="el-icon-download"></i>
              导出
            </el-button>
            <el-button type="primary" @click="openExportDialog" class="custom-export-btn">
              <i class="el-icon-setting"></i>
              自定义导出
            </el-button>
            <el-button type="warning" @click="downloadTemplate" class="template-btn">
              <i class="el-icon-document"></i>
              下载模板
            </el-button>
            <!-- 隐藏的文件输入框 -->
            <input
              type="file"
              ref="fileInput"
              style="display: none"
              accept=".xlsx, .xls"
              @change="handleFileChange"
            />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 表格区域 -->
      <el-card class="table-card" shadow="hover">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          class="data-table"
          highlight-current-row
          element-loading-text="加载中..."
          element-loading-spinner="el-icon-loading"
        >
          <el-table-column type="index" label="序号" width="70" align="center"/>
          <el-table-column prop="configurationType" label="配置类型" min-width="120" show-overflow-tooltip align="center"/>
          <el-table-column prop="basicPrice" label="基础价格" min-width="100" align="right">
            <template #default="scope">
              {{ scope.row.basicPrice ? Number(scope.row.basicPrice).toFixed(2) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="pricePerMeter" label="每米价格" min-width="100" align="right">
            <template #default="scope">
              {{ scope.row.pricePerMeter ? Number(scope.row.pricePerMeter).toFixed(2) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="increaseLength" label="增加长度" min-width="100" align="right">
            <template #default="scope">
              {{ scope.row.increaseLength ? Number(scope.row.increaseLength).toFixed(2) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="price" label="核价" min-width="100" align="right">
            <template #default="scope">
              {{ scope.row.price ? Number(scope.row.price).toFixed(2) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="installationCosts" label="安装费" min-width="100" align="right">
            <template #default="scope">
              {{ scope.row.installationCosts ? Number(scope.row.installationCosts).toFixed(2) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="project" label="项目名称" min-width="120" show-overflow-tooltip align="center"/>
          <el-table-column prop="configuration" label="配置" min-width="120" show-overflow-tooltip align="center"/>
          <el-table-column prop="createTime" label="创建时间" min-width="160" align="center">
            <template #default="scope">
              {{ scope.row.createTime ? dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" fixed="right" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <el-button type="info" size="small" @click="showViewDialog(scope.row)" class="view-btn">
                  <i class="el-icon-view"></i>
                  查看
                </el-button>
                <el-button type="primary" size="small" @click="showEditDialog(scope.row)" class="edit-btn">
                  <i class="el-icon-edit"></i>
                  编辑
                </el-button>
                <el-button type="danger" size="small" @click="handleDelete(scope.row)" class="delete-btn">
                  <i class="el-icon-delete"></i>
                  删除
                </el-button>
                <el-switch 
                  v-model="scope.row.activate"
                  class="ml-2"
                  inline-prompt
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;margin-left: 15px"
                  active-text="生效"
                  inactive-text="作废"
                  :active-value="1"
                  :inactive-value="0"
                  @change="activateChange($event === 1, scope.row.id)" 
                />
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.limit"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>

    <!-- 新增/编辑弹框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleClose"
      custom-class="increase-machine-pricing-dialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="increase-machine-pricing-form"
      >
        <el-card class="form-card" shadow="never">
          <template #header>
            <div class="form-header">
              <i class="el-icon-document"></i>
              <span>基本信息</span>
            </div>
          </template>
          <el-form-item label="项目名称" prop="project">
            <el-select v-model="formData.project" placeholder="请选择项目名称" clearable class="full-width">
              <el-option 
                v-for="item in projectList" 
                :key="item.name" 
                :label="item.name" 
                :value="item.name" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="配置类型" prop="configurationType">
            <el-input v-model="formData.configurationType" placeholder="请输入配置类型"></el-input>
          </el-form-item>
          <el-form-item label="基础价格" prop="basicPrice">
            <el-input v-model="formData.basicPrice"  
            @input="handleValueChange"
            ></el-input>

          </el-form-item>
          <el-form-item label="每米价格" prop="pricePerMeter">
            <el-input v-model="formData.pricePerMeter"  
            @input="handleValueChange"
            ></el-input>
          </el-form-item>
          <el-form-item label="需求米数" prop="increaseLength"
          @input="handleValueChange"
          >
            <el-input v-model="formData.increaseLength"></el-input>
          </el-form-item>
          <el-form-item label="核价" prop="price">
            <el-input v-model="formData.price" disabled placeholder="自动计算"></el-input>
          </el-form-item>
          <el-form-item label="安装费" prop="installationCosts" >
            <el-input v-model="formData.installationCosts" disabled  placeholder="自动计算"> </el-input>
          </el-form-item>

          <el-form-item label="配置" prop="configuration">
            <el-input
              v-model="formData.configuration"
              type="textarea"
              :rows="3"
              placeholder="请输入配置"
            ></el-input>
          </el-form-item>
        </el-card>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看弹框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="查看提升机核价"
      width="600px"
      custom-class="increase-machine-pricing-dialog view-dialog"
    >
      <el-form
        :model="viewForm"
        label-width="120px"
        class="increase-machine-pricing-form"
      >
        <el-card class="form-card" shadow="never">
          <template #header>
            <div class="form-header">
              <i class="el-icon-document"></i>
              <span>基本信息</span>
            </div>
          </template>
          <el-form-item label="项目名称">
            <el-input v-model="viewForm.project" disabled />
          </el-form-item>
          <el-form-item label="配置类型">
            <el-input v-model="viewForm.configurationType" disabled />
          </el-form-item>
          <el-form-item label="基础价格">
            <el-input v-model="viewForm.basicPrice" disabled />
          </el-form-item>
          <el-form-item label="每米价格">
            <el-input v-model="viewForm.pricePerMeter" disabled />
          </el-form-item>
          <el-form-item label="增加长度">
            <el-input v-model="viewForm.increaseLength" disabled />
          </el-form-item>
          <el-form-item label="核价">
            <el-input v-model="viewForm.price" disabled />
          </el-form-item>
          <el-form-item label="安装费">
            <el-input v-model="viewForm.installationCosts" disabled />
          </el-form-item>
  
          <el-form-item label="配置">
            <el-input 
              v-model="viewForm.configuration" 
              type="textarea"
              :rows="3"
              disabled 
            />
          </el-form-item>
        </el-card>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeViewDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 自定义导出弹框 -->
    <el-dialog
      v-model="exportDialog.visible"
      title=""
      :width="680"
      custom-class="export-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <template #header>
        <div class="export-dialog-header">
          <div class="header-left">
            <i class="header-icon el-icon-setting"></i>
            <div>
              <div class="header-title">自定义导出设置</div>
              <div class="header-subtitle">选择您需要导出的数据字段</div>
            </div>
          </div>
          <div class="selected-count">
            已选择 {{ selectedExportFields.length }} / {{ exportFieldList.length }} 项
          </div>
        </div>
      </template>
      
      <div class="export-content">
        <div class="export-toolbar">
          <div class="toolbar-left">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleSelectAllFields(true)"
              :disabled="selectedExportFields.length === exportFieldList.length"
            >
              <i class="el-icon-switch-button"></i>
              全选
            </el-button>
            <el-button 
              size="small" 
              @click="handleSelectAllFields(false)"
              :disabled="selectedExportFields.length === 0"
            >
              <i class="el-icon-refresh"></i>
              清空
            </el-button>
          </div>
          <div class="toolbar-right">
            <el-input
              v-model="fieldSearchText"
              size="small"
              placeholder="搜索字段..."
              prefix-icon="el-icon-search"
              clearable
              style="width: 200px"
            />
          </div>
        </div>
        
        <div class="field-list-container">
          <div class="field-grid">
            <div 
              v-for="field in filteredExportFields" 
              :key="field.fieldName"
              class="field-card"
              :class="{ 'selected': selectedExportFields.includes(field.fieldName) }"
              @click="toggleField(field.fieldName)"
            >
              <div class="field-card-content">
                <el-checkbox 
                  :model-value="selectedExportFields.includes(field.fieldName)"
                  @change="() => toggleField(field.fieldName)"
                  @click.stop=""
                  class="field-checkbox"
                />
                <div class="field-info">
                  <div class="field-name">{{ field.displayName }}</div>
                  <div class="field-key">{{ field.fieldName }}</div>
                </div>
                <div class="field-icon">
                  <i v-if="selectedExportFields.includes(field.fieldName)" class="el-icon-check check-icon"></i>
                </div>
              </div>
            </div>
          </div>
          
          <div v-if="filteredExportFields.length === 0" class="empty-state">
            <i class="el-icon-search empty-icon"></i>
            <div class="empty-text">未找到匹配的字段</div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="export-footer">
          <div class="footer-info">
            <i class="el-icon-info"></i>
            <span>将按当前查询条件导出选中字段的数据</span>
          </div>
          <div class="footer-buttons">
            <el-button @click="closeExportDialog" size="large">
              <i class="el-icon-close"></i>
              取消
            </el-button>
            <el-button 
              type="primary" 
              @click="confirmCustomExport" 
              :loading="loading"
              size="large"
              :disabled="selectedExportFields.length === 0"
            >
              <i class="el-icon-download"></i>
              导出 Excel
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 文件上传组件（隐藏） -->
    <input
      ref="fileInput"
      type="file"
      accept=".xlsx,.xls"
      style="display: none"
      @change="handleFileChange"
    />
  </el-main>
</template>

<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
import { nextTick, onMounted, onUnmounted, reactive, ref, computed } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { getListApi, addApi,getPriceApi, editApi, deleteApi, exportIncreaseMachinePricing, importIncreaseMachinePricing, downloadTemplate as downloadTemplateApi, updateStatusApi } from '@/api/increaseMachinePricing/index.ts'
import { IncreaseMachinePricing } from '@/api/increaseMachinePricing/type.ts'
import dayjs from 'dayjs'
import { getSimpleProject, getSimpleProjectAll } from "@/api/project"; // 导入获取项目列表的API

// 定义类型
interface IncreaseMachinePricingListParam {
  page: number;
  limit: number;
  configurationType?: string;
  project?: string;
  configuration?: string;
  activate?: number;
}

interface ExportFieldInfo {
  fieldName: string;
  displayName: string;
}

// ----------------------- 组件状态定义 -----------------------
// 表格高度自适应
const tableHeight = ref(0)

// 可导出字段列表
const exportFieldList = ref<ExportFieldInfo[]>([
  { fieldName: 'configurationType', displayName: '配置类型' },
  { fieldName: 'basicPrice', displayName: '基础价格' },
  { fieldName: 'pricePerMeter', displayName: '每米价格' },
  { fieldName: 'increaseLength', displayName: '增加长度' },
  { fieldName: 'price', displayName: '核价' },
  { fieldName: 'installationCosts', displayName: '安装费' },
  { fieldName: 'project', displayName: '项目名称' },
  { fieldName: 'configuration', displayName: '配置' },
  { fieldName: 'createTime', displayName: '创建时间' }
])

// 自定义导出弹窗状态
const exportDialog = reactive({
  visible: false
})

// 选中的导出字段
const selectedExportFields = ref<string[]>([])

// 字段搜索文本
const fieldSearchText = ref('')

// 过滤后的导出字段列表
const filteredExportFields = computed(() => {
  if (!fieldSearchText.value) {
    return exportFieldList.value
  }
  return exportFieldList.value.filter(field => 
    field.displayName.toLowerCase().includes(fieldSearchText.value.toLowerCase()) ||
    field.fieldName.toLowerCase().includes(fieldSearchText.value.toLowerCase())
  )
})

// 切换字段选中状态
const toggleField = (fieldName: string) => {
  const index = selectedExportFields.value.indexOf(fieldName)
  if (index > -1) {
    selectedExportFields.value.splice(index, 1)
  } else {
    selectedExportFields.value.push(fieldName)
  }
}

// ----------------------- 表格相关 -----------------------
const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)

const searchForm = reactive<IncreaseMachinePricingListParam>({
  page: 1,
  limit: 10,
  configurationType: '',
  project: '',
  configuration: '',
  activate: undefined
})

// 修改状态的参数
const updateStatus = reactive({
  id: undefined as number | undefined,
  activate: undefined as boolean | undefined
})

// 标志位：防止初始化时触发
const isDataLoaded = ref(false)

// 激活/作废状态切换
const activateChange = async (val: boolean, id: number) => {
  // 如果数据还没加载完成，不执行更新操作
  if (!isDataLoaded.value) return
  
  updateStatus.id = id
  updateStatus.activate = val
  try {
    await updateStatusApi({ id, activate: val ? 1 : 0 })
    ElMessage.success('操作成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const formData = reactive({
  id: undefined as number | undefined,
  configurationType: '进口',
  basicPrice: 125000,
  pricePerMeter: 4500,
  increaseLength: undefined as number | undefined,
  price: undefined as number | undefined,
  installationCosts: undefined as number | undefined,
  project: '',
  configuration: '',
  sum: undefined as number | undefined
})

const viewForm = reactive({
  id: undefined as number | undefined,
  configurationType: '',
  basicPrice: undefined as number | undefined,
  pricePerMeter: undefined as number | undefined,
  increaseLength: undefined as number | undefined,
  price: undefined as number | undefined,
  installationCosts: undefined as number | undefined,
  project: '',
  configuration: ''
})

const rules = {
  increaseLength: [
    { required: true, message: '请输入需求米数', trigger: 'blur' }
  ],
  project: [
    { required: true, message: '请输入项目', trigger: 'blur' }
  ]
}

const dialogTitle = computed(() => {
  return isEdit.value ? '编辑提升机核价' : '新增提升机核价'
})

// ----------------------- 表格数据处理 ----------------------
// 定义项目接口类型
interface Project {
  id: number;
  name: string;
}
// 项目列表
const projectList = ref<Project[]>([])
// 获取项目列表
const getProjectList = async () => {
  try {
    const res = await getSimpleProject()
    if (res && res.data) {
      projectList.value = res.data
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

// 监听值变化
const handleValueChange = () => {
  calculateSum()
}

// 自动计算合计
const calculateSum = async () => {
  if(formData.increaseLength !== undefined && formData.basicPrice !== undefined && formData.pricePerMeter !== undefined){
  const res = await getPriceApi(formData)
  if(res && res.data){
      formData.price = res.data.price
      formData.installationCosts = res.data.installationCosts
    }
  }
}

const fetchData = async () => {
  loading.value = true
  isDataLoaded.value = false // 数据加载开始，设置标志位为false
  try {
    const response = await getListApi(searchForm)
    if (response.code === 200) {
      tableData.value = response.data.list
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取数据失败')
    }
    // 使用nextTick确保DOM更新完成后再设置标志位
    await nextTick()
    isDataLoaded.value = true // 数据加载完成，设置标志位为true
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  searchForm.page = 1
  searchForm.limit = 10
  searchForm.configurationType = ''
  searchForm.project = ''
  searchForm.configuration = ''
  searchForm.activate = undefined
  fetchData()
}

// ----------------------- 新增/编辑表单相关 -----------------------
const formRef = ref<FormInstance>()

// 显示新增对话框
const showAddDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
  formData.id = undefined
  formData.configurationType = '进口'
  formData.basicPrice = 125000
  formData.pricePerMeter = 4500
  formData.increaseLength = undefined
  formData.price = undefined
  formData.installationCosts = undefined
  formData.project = ''
  formData.configuration = ''
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 显示编辑对话框
const showEditDialog = (row: IncreaseMachinePricing) => {
  isEdit.value = true
  dialogVisible.value = true
  formData.id = row.id
  formData.configurationType = row.configurationType || ''
  formData.basicPrice = row.basicPrice
  formData.pricePerMeter = row.pricePerMeter
  formData.increaseLength = row.increaseLength
  formData.price = row.price
  formData.installationCosts = row.installationCosts
  formData.project = row.project || ''
  formData.configuration = row.configuration || ''
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 显示查看对话框
const showViewDialog = (row: IncreaseMachinePricing) => {
  viewDialogVisible.value = true
  Object.assign(viewForm, row)
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 关闭查看对话框
const closeViewDialog = () => {
  viewDialogVisible.value = false
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true
    
    // 创建提交数据，只包含必要字段
    const submitData = {
      ...formData,
      isDelete: 0,
      createTime: undefined,
      updateTime: undefined,
      createBy: undefined,
      updateBy: undefined
    } as IncreaseMachinePricing
    
    const api = isEdit.value ? editApi : addApi
    const response = await api(submitData)
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      handleClose()
      fetchData()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// ----------------------- 删除相关 -----------------------
const handleDelete = async (row: IncreaseMachinePricing) => {
  try {
    await ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteApi(row.id!)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  searchForm.limit = val
  searchForm.page = 1
  fetchData()
}

// 当前页变化
const handleCurrentChange = (val: number) => {
  searchForm.page = val
  fetchData()
}

// ----------------------- 导入导出相关 -----------------------
const fileInput = ref<HTMLInputElement>()

// 导出数据
const exportData = async () => {
  try {
    await exportIncreaseMachinePricing()
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 处理导入
const handleImport = () => {
  fileInput.value?.click()
}

// 文件选择变化
const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  // 验证文件类型
  const validTypes = [
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-excel'
  ]
  if (!validTypes.includes(file.type)) {
    ElMessage.error('请选择Excel文件')
    return
  }

  try {
    const response = await importIncreaseMachinePricing(file)
    if (response.code === 200) {
      ElMessage.success('导入成功')
      fetchData()
    } else {
      ElMessage.error(response.message || '导入失败')
    }
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败')
  } finally {
    // 清空文件输入框
    target.value = ''
  }
}

// 下载模板
const downloadTemplate = async () => {
  try {
    await downloadTemplateApi()
    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载模板失败')
  }
}

// 打开自定义导出弹窗
const openExportDialog = () => {
  exportDialog.visible = true
  // 默认选中所有字段
  selectedExportFields.value = exportFieldList.value.map(field => field.fieldName)
}

// 关闭自定义导出弹窗
const closeExportDialog = () => {
  exportDialog.visible = false
}

// 全选/取消全选导出字段
const handleSelectAllFields = (checked: boolean) => {
  if (checked) {
    selectedExportFields.value = exportFieldList.value.map(field => field.fieldName)
  } else {
    selectedExportFields.value = []
  }
}

// 确认自定义导出
const confirmCustomExport = async () => {
  if (selectedExportFields.value.length === 0) {
    ElMessage.warning('请至少选择一个导出字段')
    return
  }
  
  try {
    loading.value = true
    // 这里调用自定义导出API，需要在API中实现
    await exportIncreaseMachinePricing() // 暂时使用普通导出，后续可扩展
    ElMessage.success('导出成功')
    closeExportDialog()
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// ----------------------- 生命周期钩子 -----------------------
onMounted(() => {
    getProjectList()

  fetchData()
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped lang="scss">
.increase-machine-pricing-main {
  padding: 0;
}

.main-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
  
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  
  .el-form-item {
    margin-bottom: 0;
    margin-right: 16px;
  }
  
  .search-buttons {
    margin-left: auto;
    
    .el-button {
      margin-left: 8px;
      transition: all 0.3s;
      
      &:first-child {
        margin-left: 0;
      }
    }
    
    .search-btn {
      background: linear-gradient(135deg, #1989fa, #0056b3);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
      }
    }
    
    .add-btn {
      background: linear-gradient(135deg, #67c23a, #409eff);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
      }
    }
    
    .reset-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(144, 147, 153, 0.2);
    }
    
    .custom-export-btn {
      background: linear-gradient(135deg, #409EFF, #1989fa);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
      }
    }
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 0;
  
  :deep(.el-card__body) {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.data-table {
  border-radius: 4px;
  flex: 1;
  
  :deep(.el-table__header-wrapper) {
    th {
      background-color: #f2f6fc;
      font-weight: 600;
    }
  }
  
  :deep(.el-table__row) {
    &:hover {
      td {
        background-color: #ecf5ff;
      }
    }
  }
  
  .action-buttons {
    display: flex;
    justify-content: center;
    
    .el-button {
      padding: 6px 10px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
    }
    
    .view-btn {
      margin-right: 0px;
    }
    
    .edit-btn {
      margin-right: 0px;
    }
  }
}

.pagination {
  padding: 15px 20px;
  justify-content: flex-end;
  background: #fff;
  border-radius: 0 0 8px 8px;
}

.increase-machine-pricing-form {
  padding: 20px;

  .form-card {
    margin-bottom: 15px;
    border-radius: 8px;
    transition: all 0.3s;
    overflow: hidden;
    border: 1px solid #ebeef5;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    :deep(.el-card__header) {
      padding: 10px 15px;
      background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
      border-bottom: 1px solid #e1f3d8;
    }
    
    .form-header {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
      display: flex;
      align-items: center;
      
      i {
        margin-right: 8px;
        color: #67c23a;
      }
    }
  }
  
  :deep(.el-form-item__label) {
    color: #606266;
    font-weight: 500;
  }
  
  :deep(.el-input) {
    .el-input__inner {
      transition: all 0.3s;
      
      &:hover, &:focus {
        border-color: #67c23a;
      }
    }
  }
  
  :deep(.el-button--primary) {
    background-color: #67c23a;
    border-color: #67c23a;
    
    &:hover {
      opacity: 0.9;
    }
  }
}

:deep(.increase-machine-pricing-dialog) {
  .el-dialog__header {
    border-bottom: 1px solid #ebeef5;
    padding: 15px 20px;
    margin-right: 0;
    
    .el-dialog__title {
      color: #67c23a;
      font-weight: 600;
    }
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .el-dialog__footer {
    border-top: 1px solid #ebeef5;
    padding: 15px 20px;
  }
}

.view-dialog {
  :deep(.el-dialog__header) {
    border-bottom: 1px solid #ebeef5;
    padding: 15px 20px;
    
    .el-dialog__title {
      color: #409EFF;
      font-weight: 600;
    }
  }
}

// 自定义导出弹窗样式
:deep(.export-dialog) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  
  .el-dialog__header {
    padding: 0;
    margin-right: 0;
    border-bottom: none;
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .el-dialog__footer {
    padding: 0;
    border-top: none;
  }
}

.export-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 20px;
  color: white;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .header-icon {
      font-size: 28px;
      background: rgba(255, 255, 255, 0.2);
      padding: 12px;
      border-radius: 50%;
      backdrop-filter: blur(10px);
    }
    
    .header-title {
      font-size: 20px;
      font-weight: 600;
      margin-bottom: 4px;
    }
    
    .header-subtitle {
      font-size: 14px;
      opacity: 0.9;
    }
  }
  
  .selected-count {
    background: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(10px);
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    border: 1px solid rgba(255, 255, 255, 0.2);
  }
}

.export-content {
  padding: 24px;
  
  .export-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px 20px;
    background: #f8fafc;
    border-radius: 10px;
    border: 1px solid #e2e8f0;
    
    .toolbar-left {
      display: flex;
      gap: 12px;
      
      .el-button {
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        
        &:disabled {
          transform: none;
          box-shadow: none;
        }
      }
    }
    
    .toolbar-right {
      :deep(.el-input) {
        .el-input__wrapper {
          border-radius: 8px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
          border: 1px solid #e2e8f0;
          transition: all 0.3s;
          
          &:hover, &.is-focus {
            border-color: #667eea;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
          }
        }
      }
    }
  }
  
  .field-list-container {
    .field-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 16px;
      max-height: 400px;
      overflow-y: auto;
      padding-right: 8px;
      
      &::-webkit-scrollbar {
        width: 6px;
      }
      
      &::-webkit-scrollbar-track {
        background: #f1f5f9;
        border-radius: 3px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: #cbd5e1;
        border-radius: 3px;
        
        &:hover {
          background: #94a3b8;
        }
      }
    }
    
    .field-card {
      background: white;
      border: 2px solid #e2e8f0;
      border-radius: 12px;
      padding: 16px;
      cursor: pointer;
      transition: all 0.3s ease;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
      
      &:hover {
        border-color: #667eea;
        transform: translateY(-4px);
        box-shadow: 0 8px 24px rgba(102, 126, 234, 0.15);
      }
      
      &.selected {
        border-color: #667eea;
        background: linear-gradient(135deg, #f0f4ff 0%, #e6f0ff 100%);
        box-shadow: 0 4px 16px rgba(102, 126, 234, 0.2);
        
        .field-card-content {
          .field-name {
            color: #667eea;
            font-weight: 600;
          }
          
          .field-key {
            color: #4c51bf;
          }
        }
      }
      
      .field-card-content {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .field-checkbox {
          flex-shrink: 0;
          
          :deep(.el-checkbox__input) {
            .el-checkbox__inner {
              border-radius: 6px;
              border-width: 2px;
              width: 18px;
              height: 18px;
              
              &:hover {
                border-color: #667eea;
              }
            }
            
            &.is-checked .el-checkbox__inner {
              background-color: #667eea;
              border-color: #667eea;
            }
          }
        }
        
        .field-info {
          flex: 1;
          min-width: 0;
          
          .field-name {
            font-size: 15px;
            font-weight: 500;
            color: #1e293b;
            margin-bottom: 4px;
            word-break: break-all;
          }
          
          .field-key {
            font-size: 12px;
            color: #64748b;
            font-family: 'Monaco', 'Menlo', monospace;
            background: #f1f5f9;
            padding: 2px 6px;
            border-radius: 4px;
            display: inline-block;
          }
        }
        
        .field-icon {
          flex-shrink: 0;
          width: 24px;
          height: 24px;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .check-icon {
            font-size: 18px;
            color: #667eea;
            animation: checkIn 0.3s ease;
          }
        }
      }
    }
    
    .empty-state {
      text-align: center;
      padding: 60px 20px;
      color: #64748b;
      
      .empty-icon {
        font-size: 48px;
        margin-bottom: 16px;
        opacity: 0.5;
      }
      
      .empty-text {
        font-size: 16px;
      }
    }
  }
}

.export-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
  
  .footer-info {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #64748b;
    font-size: 14px;
    
    i {
      color: #3b82f6;
    }
  }
  
  .footer-buttons {
    display: flex;
    gap: 12px;
    
    .el-button {
      border-radius: 8px;
      font-weight: 500;
      padding: 12px 24px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      }
      
      &.el-button--primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        
        &:hover {
          opacity: 0.9;
        }
        
        &:disabled {
          background: #e2e8f0;
          color: #94a3b8;
          transform: none;
          box-shadow: none;
        }
      }
      
      i {
        margin-right: 6px;
      }
    }
  }
}

@keyframes checkIn {
  0% {
    transform: scale(0) rotate(180deg);
    opacity: 0;
  }
  100% {
    transform: scale(1) rotate(0deg);
    opacity: 1;
  }
}

// 响应式调整
@media (max-width: 768px) {
  .search-form {
    .el-form-item {
      margin-bottom: 10px;
    }
    
    .search-buttons {
      width: 100%;
      margin-left: 0;
      display: flex;
      justify-content: space-between;
    }
  }
  
  .table-card {
    height: calc(100vh - 230px);
  }
  
  .increase-machine-pricing-form {
    padding: 10px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  :deep(.export-dialog) {
    width: 95vw !important;
    margin: 5vh auto;
  }
  
  .export-dialog-header {
    padding: 20px 16px 16px;
    
    .header-left {
      gap: 12px;
      
      .header-icon {
        font-size: 24px;
        padding: 10px;
      }
      
      .header-title {
        font-size: 18px;
      }
      
      .header-subtitle {
        font-size: 13px;
      }
    }
    
    .selected-count {
      padding: 6px 12px;
      font-size: 13px;
    }
  }
  
  .export-content {
    padding: 16px;
    
    .export-toolbar {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;
      padding: 12px 16px;
      
      .toolbar-left {
        justify-content: center;
      }
      
      .toolbar-right {
        :deep(.el-input) {
          width: 100% !important;
        }
      }
    }
    
    .field-list-container {
      .field-grid {
        grid-template-columns: 1fr;
        gap: 12px;
        max-height: 300px;
      }
      
      .field-card {
        padding: 12px;
        
        .field-card-content {
          gap: 10px;
          
          .field-info {
            .field-name {
              font-size: 14px;
            }
            
            .field-key {
              font-size: 11px;
            }
          }
        }
      }
    }
  }
  
  .export-footer {
    flex-direction: column;
    gap: 12px;
    padding: 16px;
    
    .footer-info {
      text-align: center;
      font-size: 13px;
    }
    
    .footer-buttons {
      width: 100%;
      justify-content: center;
      
      .el-button {
        flex: 1;
        padding: 10px 20px;
      }
    }
  }
}

@media (max-width: 480px) {
  .export-content {
    .field-list-container {
      .field-grid {
        max-height: 250px;
      }
    }
  }
}
</style> 